import React,{Component} from 'react';
import Record from './Record';
import RecordForm from './RecordForm'
import Amount from  './Amount'
import * as RecordAPI from '../utils/RecordAPI'
import './mock';

export default  class Records extends Component {
  constructor(){
    super();
    this.state={
      error: null,
      isLoaded: false,
      records: []
    };
  }

  componentDidMount(){
    RecordAPI.getAll().then(res=>
      this.setState({
        isLoaded:true,
        records: res.data.record
      })
    ).catch(error=>
        this.setState({
          isLoaded: true,
          error
        })  
    )
  }

  addRecord(record){
    this.setState({
      error: null,
      isLoaded: true,
      records: [
        ...this.state.records,
        record
      ]
    })
  }

  editRecord(record,data){
    console.log(record)
    console.log(data)
    const recordIndex=this.state.records.indexOf(record);
    const newRecords=this.state.records.map((item,index)=>{
      if (index!==recordIndex){
        return item
      }else{
        return {
          ...item,
          ...data
        }
      }
    })
    this.setState({
     records: newRecords
    })
  }

  handleDelete(record){
    const recordIndex=this.state.records.indexOf(record);
    let newRecords= this.state.records.filter((item,index)=>index!==recordIndex)
    this.setState({
      records: newRecords
   })
  }

  credit(){
    let credit=this.state.records.filter(record=>record.amount>=0)
    return credit.reduce((pre,curr)=>pre+parseInt(curr.amount),0)
  }

  debit(){
    let debit=this.state.records.filter(record=>record.amount<0)
    return debit.reduce((pre,curr)=>pre+parseInt(curr.amount),0)
  }

  balance(){
    return this.credit()+this.debit()   
  }


  render(){
    const {error,isLoaded,records}=this.state;
    let recordComponent;
    if(error){
      recordComponent= <div>ERROR</div>
    }else if(!isLoaded){
      recordComponent= <div>Loading...</div>
    }else{
      recordComponent= (  
        <table className='table table-bordered'>
          <thead>
            <tr>
              <th>Date</th>
              <th>Title</th>
              <th>Amount</th>
              <th>Action</th>
            </tr>
          </thead>
          <tbody>
            {records.map((record)=>
            <Record key={record.id} record={record} 
            handleEditRecord={this.editRecord.bind(this)} 
            handleDelete={this.handleDelete.bind(this)}/>)}
          </tbody>
        </table> 
      );
    } 
    return (
      <div>
        <h2>Records</h2>
        <div className='row mb-3'>
          <Amount text='Credit' type='success' amount={this.credit()}></Amount>
          <Amount text='Debit' type='danger' amount={this.debit()}></Amount>
          <Amount text='Balance' type='info' amount={this.balance()}></Amount>
        </div>
        <RecordForm handleNewRecord={this.addRecord.bind(this)}/>
        {recordComponent}
      </div>
    ) 
  }
  
}

